/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  ZoneSearchActivity.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-13 下午3:38:46   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.LActivity;
import com.jiyi.bean.zone.SearchBean;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.bean.zone.ZoneQunZuBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.event.ZoneSearchEvent;
import com.jiyi.inteface.ClearEditTextInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: ZoneSearchActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-13 下午3:38:46
 * 
 */
public class ZoneSearchActivity extends LActivity implements
		ClearEditTextInterface {

	@BindView(R.id.root)
	LinearLayout root;

	@BindView(R.id.ivBack)
	ImageView ivBack;
	@BindView(R.id.etSearch)
	ClearEditText etSearch;
	@BindView(R.id.rlContent)
	RelativeLayout rlContent;

	private Fragment[] Fragments = { new ZoneSearchNullFragment(),
			new ZoneSearchAllFragment() };
	// 搜索的类别 0 社区全部（活动、群组、好友） 1：活动 2：群组 3：好友
	int type = 0;
	
	//获取的群组数据
	List<ZoneHaoYouBean> haoYouDatas = new ArrayList<ZoneHaoYouBean>();

	//获取的群组数据
	List<ZoneQunZuBean> qunZuDatas = new ArrayList<ZoneQunZuBean>();
	
	//获取的群组数据
	List<ZoneHuoDongBean> huoDongDatas = new ArrayList<ZoneHuoDongBean>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zone_search);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		EventBus.getDefault().register(this);
	}
	
	@Subscribe
	public void onSearch(ZoneSearchEvent zoneSearchEvent)
	{
		String content = zoneSearchEvent.searchContent;
		etSearch.setText(content);
		search(type);
	}

	@Override
	public void onBackPressed() {
		onBackActivity(root);
	}
	
	@Override
	protected void onStop() {
		EventBus.getDefault().unregister(this);
		super.onStop();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-13
	 */
	private void init() {
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
			//获取前面点击的对象
			x = getIntent().getIntExtra("x", 0);
			y = getIntent().getIntExtra("y", 0);
			//初始化开场动画和退场动画
			setupAnimator(root,x,y);
		}

		getIntentData();

		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					search(type);
					return true;
				}
				return false;
			}
		});
		etSearch.setClearEditTextInterface(this);
		onClear();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-13
	 */
	private void getIntentData() {
		type = getIntent().getIntExtra("type", 0);
		switch (type) {
		case 1:
			etSearch.setHint("活动搜索");
			break;
		case 2:
			etSearch.setHint("群组搜索");
			break;
		case 3:
			etSearch.setHint("好友搜索");
			break;
		default:
			break;
		}
	}

	void search(int type) {
		if (TextUtils.isEmpty(etSearch.getText())) {
			ToastUtil.getInstances().showMsg("请先输入搜索条件");
			return;
		}
		//执行搜索
		searchAll(etSearch.getText().toString(),type);
	}

	private void setFragment(Fragment fragment, String tag) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	    imm.hideSoftInputFromWindow(etSearch.getWindowToken(),0);
	    
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.replace(R.id.rlContent, fragment, tag);
		transaction.commit();
	}

	@Override
	public void onClear() {
		if (type == 0) {
			setFragment(Fragments[0], "null");
		}
	}
	
	@OnClick({ R.id.ivBack})
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ivBack:
			onBackActivity(root);
			break;
		default:
			break;
		}
	}

	@Override
	public void onAnimatStop() {
		finish();
	}
	
	/**   
	 * @author: HYM 
	 * @Title: searchAll   
	 * @Description: TODO(搜索接口)   
	 * @param keyword
	 * @param type void 
	 * @date: 2017-7-18
	 */  
	void searchAll(String keyword,final int type)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("key", etSearch.getText().toString());
		params.put("agf", type+"");

		VolleyRequest.StringRequestPost(this, WebApi.ZONE_SEARCH_ALL, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								SearchBean temp = new Gson().fromJson(result, SearchBean.class);
								//清除数据
								haoYouDatas.clear();
								huoDongDatas.clear();
								qunZuDatas.clear();
								if (temp == null || temp.getData() == null ) {
									
								} else {
									List<ZoneHaoYouBean> haoYouData = temp.getData().getFriendList();
									if (haoYouData != null && haoYouData.size() >0) {
										haoYouDatas.addAll(haoYouData);
									}
									List<ZoneHuoDongBean> huoDongData = temp.getData().getActivities();
									if (huoDongData != null && huoDongData.size() >0) {
										huoDongDatas.addAll(huoDongData);
									}
									List<ZoneQunZuBean> qunZuData = temp.getData().getGroups();
									if (qunZuData != null && qunZuData.size() >0) {
										qunZuDatas.addAll(qunZuData);
									}
									
									//判断当前是什么搜索
									
									Bundle bundle = null;
									Fragment fragment = null;
									//把数据传递给Fragment
									bundle = new Bundle();
									bundle.putString("haoyou",new Gson().toJson(haoYouDatas));
									bundle.putString("qunzu",new Gson().toJson(qunZuDatas));
									bundle.putString("huodong",new Gson().toJson(huoDongDatas));
									bundle.putInt("type", type);
									fragment = new ZoneSearchAllFragment();
									fragment.setArguments(bundle);
									setFragment(fragment, "all");
								}
								
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
}
